package com.offcn.bigdata.spark.p1;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

/**
 * spark入门案例之java版
 *  编程入口：SparkContext，但是java版本为JavaSparkContext
 *  同时不同的spark模块的编程入口有所差异：
 *      SQL中的模块：
 *              早期版本为SQLContext和HiveContext
 *              2.0之后统一为SparkSesson
 *      Streaming中：
 *            java： JavaStreamingContext
 *            scala：StreamingContext
 *  编程通用的步骤：
 *  1、构建编程入口XxxContext
 *      需要涉及相应的配置信息
 *  2、加载外部数据
 *  3、对加载的数据进行转换操作、
 *  4、要提交spark作业的执行
 *  5、释放资源
 */
public class JavaWordCountOps {
    public static void main(String[] args) {
        Logger.getLogger("org.apache.spark").setLevel(Level.INFO);//局部的日志管理
        SparkConf conf = new SparkConf();//相当于mr中的Configuration
        conf.setMaster("local[*]");
        conf.setAppName("JavaWordCount");
        JavaSparkContext jsc = new JavaSparkContext(conf);//相当于mr中的Job

        JavaRDD<String> linesRDD = jsc.textFile("E:/data/spark/hello.txt");

        JavaRDD<String> wordsRDD = linesRDD.flatMap(new FlatMapFunction<String, String>() {
            public Iterator<String> call(String line) throws Exception {
                String[] fields = line.split("\\s+");
                return Arrays.asList(fields).iterator();
            }
        });
//        wordsRDD.foreach(new VoidFunction<String>() {
//            public void call(String word) throws Exception {
//                System.out.println(word);
//            }
//        });
        JavaPairRDD<String, Integer> pairsRDD = wordsRDD.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String word) throws Exception {
                return new Tuple2<String, Integer>(word, 1);
            }
        });

        JavaPairRDD<String, Integer> ret = pairsRDD.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer v1, Integer v2) throws Exception {
//                int i = 1 / 0; //说明transformation操作是lazy，得需要action操作去触发
                return v1 + v2;
            }
        });

        ret.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> kv) throws Exception {
                System.out.printf("word: %s, count: %d\n", kv._1, kv._2);
            }
        });


        jsc.stop();//资源释放
    }
}
